#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "links/linkdescription.h"
#include <QSettings>
#include <QMessageBox>

MainWindow::MainWindow(LinkFactory* factory, ProxyFactory*p,QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    lFactory=factory;
    pFactory=p;
    connect(lFactory, SIGNAL(newLD(int)), this, SLOT(newLink(int)));
    connect(pFactory, SIGNAL(newPD(int)), this, SLOT(newProxy(int)));
    ui->setupUi(this);

    QWidget* widget=new QWidget(ui->scrollArea);
    layout=new QVBoxLayout();
    widget->setLayout(layout);

    layout->addStretch();
    layout->setMargin(2);
    layout->setSpacing(0);
    QSettings set("PePeL", "netControll");
    ui->ipAddress->setText(set.value("dstIP","localhost").toString());
    ui->scrollArea->setWidget(widget);

    connect(ui->actionProxy, SIGNAL(triggered()), &this->proxyAdder, SLOT(show()));

    widget=new QWidget(ui->scrollArea);
    layoutP=new QVBoxLayout();
    widget->setLayout(layoutP);

    layoutP->addStretch();
    layoutP->setMargin(2);
    layoutP->setSpacing(0);
    ui->scrollArea_2->setWidget(widget);
}

void MainWindow::newLink(int idx){
    LinkDescription* link=lFactory->getLD(idx);
    layout->takeAt(layout->count()-1);
    layout->addWidget(link);
    layout->addStretch();
};

void MainWindow::newProxy(int idx){
    ProxyDescription* link=pFactory->getPD(idx);
    layoutP->takeAt(layoutP->count()-1);
    layoutP->addWidget(link);
    layoutP->addStretch();
};

MainWindow::~MainWindow()
{
    QSettings set("PePeL", "netControll");
    set.setValue("dstIP", ui->ipAddress->text());
    delete ui;
}

void MainWindow::on_connectButton_clicked()
{
    emit connectEd(ui->ipAddress->text());
    disconnect(ui->connectButton);
    ui->ipAddress->setEnabled(false);
}

void MainWindow::connErr(QAbstractSocket::SocketError s){
    ui->ipAddress->setEnabled(true);
    connect(ui->connectButton, SIGNAL(clicked()), this, SLOT(on_connectButton_clicked()));
    switch (s) {
    case QAbstractSocket::RemoteHostClosedError:
        QMessageBox::information(this, tr("sDgui"),
                                 tr("Program zamknal polaczenie\n"));
        break;
    case QAbstractSocket::HostNotFoundError:
        QMessageBox::information(this, tr("sDgui"),
                                 tr("Nie znaleziono hosta \n"
                                    "Sprawdz IP hosta."));
        break;
    case QAbstractSocket::ConnectionRefusedError:
        QMessageBox::information(this, tr("sDgui"),
                                 tr("Host odrzucil probe polaczenia na porcie 2201\n"
                                    "Sprawdz czy program jest uruchomiony"));
        break;
    default:
        QMessageBox::information(this, tr("sDgui"),
                                 tr("Other network error"));
    }
};
